<template>
  <div class="layui-container fly-marginTop">
  <div class="fly-panel fly-panel-user" pad20>
    <div class="layui-tab layui-tab-brief" lay-filter="user">
      <ul class="layui-tab-title">
        <li><a href="login.html">登入</a></li>
        <li class="layui-this">注册</li>
      </ul>
      <div class="layui-form layui-tab-content" id="LAY_ucm" style="padding: 20px 0;">
        <div class="layui-tab-item layui-show">
          <div class="layui-form layui-form-pane">
            <form action=""  @submit.prevent="onSubmit" method="post">
              <div class="layui-form-item">
                <label for="L_email" class="layui-form-label">邮箱</label>
                <div class="layui-input-inline">
                  <input type="text" id="user_mail" name="email" required lay-verify="required|email" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">将会成为您唯一的登入名</div>
              </div>

              <div class="layui-form-item">
                <label for="L_vercode" class="layui-form-label">验证码</label>
                <div class="layui-input-inline">
                   <input type="text" id="L_vercode" name="vercode" required="" lay-verify="required" placeholder="请输入邮箱验证码" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid" style="padding: 0!important;">
                  <button type="button" class="layui-btn layui-btn-normal get_mail_code_btn" :disabled="isDisabled" @click="sendEmail" id="mail_getvercode">{{buttonName}}</button>
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_username" class="layui-form-label">昵称</label>
                <div class="layui-input-inline">
                  <input type="text" id="L_username" name="username" required lay-verify="required|username" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_pass" class="layui-form-label">密码</label>
                <div class="layui-input-inline">
                  <input type="password" id="L_pass" name="pass" required lay-verify="pass" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">6到12个字符</div>
              </div>
              <div class="layui-form-item">
                <label for="L_repass" class="layui-form-label">确认密码</label>
                <div class="layui-input-inline">
                  <input type="password" id="L_repass" name="repass" required lay-verify="required" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-form-item">
                <label for="L_vercode" class="layui-form-label">图形验证</label>
                <div class="layui-input-inline">
                  <input type="text" id="L_verify" name="verify" required lay-verify="required" placeholder="请输入图形验证码" autocomplete="off" class="layui-input">
                </div>
                <!-- <div class="layui-form-mid">
                  <img id="verify_img" src="{:captcha_src()}" alt="验证码" onclick="refreshVerify()" style="height: 38px;margin-top: -6px;">
                </div> -->
                <div class="layui-form-mid">
                  <img id="verify_img" :src="host+'/micro-bbs/v2/captcha/image/'+captcha_id" alt="验证码" @click="refreshVerify" style="height: 38px;margin-top: -6px;">
                </div>
              </div>
              <div class="layui-form-item">
                <button class="layui-btn" lay-filter="*" lay-submit>立即注册</button>
              </div>
              <div class="layui-form-item fly-form-app">
                <span>或者直接使用社交账号快捷注册</span>
                <a href="{:url('api/index/qqlogin')}" onclick="layer.msg('正在通过QQ登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-qq" title="QQ登入"></a>
                <a href="{:url('api/index/sinalogin')}" onclick="layer.msg('正在通过微博登入', {icon:16, shade: 0.1, time:0})" class="iconfont icon-weibo" title="微博登入"></a>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>
</template>
<script>
import request from '@/utils/request'
export default {
   components: {
  },
  inject:['store'],
  name: "MyRegister",
  props: ["register"],
  data() {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (userNameRule.test(value)) {
        return callback();
      }else{
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z]\w{5,17}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    // 确认密码的校验方法
    let validateConfirmPass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入确认密码"));
      }
      // 校验是否以密码一致
      if (this.RegisterUser.pass != "" && value === this.RegisterUser.pass) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("两次输入的密码不一致"));
      }
    };
    return {
      isRegister: true, // 控制注册组件是否显示
      RegisterUser: {
        name: "",
        pass: "",
        confirmPass: "",
        phone: "",
        code: ""
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        name: [{ validator: validateName, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        confirmPass: [{ validator: validateConfirmPass, trigger: "blur" }]
      },
      buttonName: "获取验证码",
			isDisabled: false,
			time: 90,
      captcha_id: "",
      host: "http://127.0.0.1:8080"
    };
  },
  watch: {
    // 监听父组件传过来的register变量，设置this.isRegister的值
    register: function(val) {
      if (val) {
        this.isRegister = val;
      }
    },
    // 监听this.isRegister变量的值，更新父组件register变量的值
    isRegister: function(val) {
      if (!val) {
        this.$refs["ruleForm"].resetFields();
        this.$emit("fromChild", val);
      }
    }
  },
  mounted(){
    this.refreshVerify()
  },
  methods: {
    onSubmit() {
      console.log("方法进来了")
      this.Register()
    },
    Register() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(valid => {
        //如果通过校验开始注册
        console.log("valid",valid)
        if (valid) {
          var params = new URLSearchParams();
          params.append('username', this.RegisterUser.name);
          params.append('password', this.RegisterUser.pass);
          params.append('telephone', this.RegisterUser.phone);
          params.append('authCode', this.RegisterUser.code);

          request.post('oauth/register', params).then((res) => {
            const { code, data, message } = res
            if (code === 200) {
              // 隐藏注册组件
              this.isRegister = false;
              console.log("data",data)
              this.notifySucceed(message);
            }else{
              this.notifySucceed(message);
            }
          })
        } else {
          return false;
        }
      });
    },
    //获取验证码
    refreshVerify() {
      const params = {
        params: {
        }
      }
      request.get('/micro-bbs/v2/captcha/generate', params).then((res) => {
        const { code, data } = res
        if (code === 200) {
          this.captcha_id = data.id
        }
      })
    },
    //发送邮箱
    sendEmail() {
      const params = {
        params: {
          to_email: this.to_email,
        }
      }
      request.get('/micro-bbs/v2/email/sendCode', params).then((res) => {
        console.log("res:",res)
        const { code, data } = res
        if (code === 200) {
          console.log("data:",data)
          this.timestart()
        }
      })
    },
    //倒计时
    timestart() {
      let me = this;
      me.isDisabled = true;
      let interval = window.setInterval(function() {
        me.buttonName = '（' + me.time + '秒）后重发';
        --me.time;
        if(me.time < 0) {
          me.buttonName = "重新发送";
          me.time = 90;
          me.isDisabled = false;
          window.clearInterval(interval);
        }
      }, 1000);
    }
  }
};
</script>